/**
 * 排班网格组件
 * 显示排班表格和班次
 */

import type { ScheduleContext, Employee, Shift, DateRange, ViewMode } from '../../../types'

interface ScheduleGridProps {
  context: ScheduleContext
  employees: Employee[]
  shifts: Shift[]
  dateRange: DateRange
  viewMode: ViewMode
}

export function ScheduleGrid({ context, employees, shifts, dateRange }: ScheduleGridProps) {
  // 辅助函数：格式化日期为 YYYY-MM-DD
  const formatDate = (date: Date): string => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  // 生成日期列表
  const generateDates = (): string[] => {
    const dates: string[] = []
    const start = new Date(dateRange.start)
    const end = new Date(dateRange.end)

    const current = new Date(start)
    while (current <= end) {
      dates.push(formatDate(current))
      current.setDate(current.getDate() + 1)
    }

    return dates
  }

  const dates = generateDates()

  const formatDateDisplay = (dateStr: string): string => {
    const date = new Date(dateStr)
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekDay = weekDays[date.getDay()]
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${weekDay}\n${month}/${day}`
  }

  const getShiftLabel = (type: string): string => {
    const labels: Record<string, string> = {
      morning: '早班',
      afternoon: '中班',
      night: '夜班',
      custom: '自定义',
    }
    return labels[type] || type
  }

  const handleCellClick = (employeeId: string | number, date: string) => {
    context.emit('cell:click', { employeeId, date })
  }

  const handleShiftClick = (shift: Shift, event: React.MouseEvent) => {
    event.stopPropagation()
    context.emit('shift:click', shift)
  }

  const handleCellContextMenu = (
    employeeId: string | number,
    date: string,
    event: React.MouseEvent
  ) => {
    event.preventDefault()
    context.emit('cell:contextMenu', { employeeId, date, x: event.clientX, y: event.clientY })
  }

  return (
    <div className="schedule-grid">
      {/* 时间头部 */}
      <div className="time-header">
        {dates.map(date => (
          <div key={date} className="time-cell">
            {formatDateDisplay(date)}
          </div>
        ))}
      </div>

      {/* 排班行 */}
      <div className="schedule-rows">
        {employees.map(employee => (
          <div key={employee.id} className="schedule-row" data-employee-id={employee.id}>
            {dates.map(date => {
              const shift = shifts.find(s => s.employeeId === employee.id && s.date === date)

              return (
                <div
                  key={`${employee.id}-${date}`}
                  className="time-slot"
                  data-employee-id={employee.id}
                  data-date={date}
                  onClick={() => handleCellClick(employee.id, date)}
                  onContextMenu={e => handleCellContextMenu(employee.id, date, e)}
                >
                  {shift && (
                    <div
                      className={`shift shift-${shift.type}`}
                      data-shift-id={shift.id}
                      onClick={e => handleShiftClick(shift, e)}
                      draggable
                      onDragStart={e => {
                        e.dataTransfer.setData('shiftId', String(shift.id))
                        context.emit('shift:dragStart', shift)
                      }}
                    >
                      <div className="shift-content">{getShiftLabel(shift.type)}</div>
                      {shift.note && <div className="shift-note">{shift.note}</div>}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        ))}

        {employees.length === 0 && <div className="schedule-empty">暂无排班数据</div>}
      </div>
    </div>
  )
}
